package com.example;

/**
 * @desc:
 * @author: Shoko
 * @date: 2025/6/1
 */
// ClientHandler.java
import java.io.*;
import java.net.*;

public class ClientHandler extends Thread {
    private Socket socket;
    private ChatGroup chatGroup;
    private Member member;
    private PrintWriter out;
    private BufferedReader in;

    public ClientHandler(Socket socket, ChatGroup chatGroup) {
        this.socket = socket;
        this.chatGroup = chatGroup;
    }

    @Override
    public void run() {
        try {
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            // 注册会员
            String memberInfo = in.readLine();
            String[] info = memberInfo.split(",");
            String type = info[0];
            String name = info[1];

            if (type.equals("diamond")) {
                member = new DiamondMember(name);
            } else {
                member = new CommonMember(name);
            }
            chatGroup.register(member);

            // 处理消息
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                String[] parts = inputLine.split(":", 3);
                String command = parts[0];
                String to = parts[1];
                String content = parts[2];

                if (command.equals("text")) {
                    member.sendText(to, content);
                } else if (command.equals("image")) {
                    member.sendImage(to, content);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}